package com.wangsd.web.sys.service;

import com.gitee.fastmybatis.core.query.Query;
import com.wangsd.common.basicbean.TreeData;
import com.wangsd.common.exception.BusinessException;
import com.wangsd.web.mqpay.entity.Customer;
import com.wangsd.web.mqpay.service.CustomerService;
import com.wangsd.web.sys.entity.SysCompany;
import com.wangsd.web.sys.entity.SysUser;
import com.wangsd.web.sys.mapper.SysCompanyMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysCompanyService {
    @Resource
    SysCompanyMapper mapper;
    @Autowired
    SysUserService userService;
    @Autowired
    CustomerService customerService;
    @Autowired
    AgentFlowService agentFlowService;

    public List<SysCompany> selectPage(SysCompany queryObj, String code) {
        Query query = new Query();
        if (StringUtils.isNotBlank(queryObj.getName())) {
            query.like("name", queryObj.getName());
        }
        if (StringUtils.isNotBlank(code)) {
            query.likeRight("code", code);
        }
        query.eq("type", queryObj.getType());
        List<SysCompany> list = mapper.list(query);
        return list;
    }
    /**
     * 根据服务商code查询所有代理商
     * @param parentCode
     * @return
     */
    private List<SysCompany> selectByParentCode(String parentCode) {
        return mapper.listByColumn("parent_code", parentCode);
    }

    public int delete(Long companyId) {
        SysCompany company = this.selectById(companyId);
        List<SysUser> userList = userService.selectByParentCode(company.getCode());
        if (userList.size() > 0) {
            throw new BusinessException("服务商下面有用户不允许删除！");
        }
        List<SysCompany> companyList = this.selectByParentCode(company.getCode());
        if (companyList.size() > 0) {
            throw new BusinessException("服务商下面有代理商不允许删除！");
        }
        List<Customer> customerList = customerService.selectByParentCode(company.getCode());
        if (customerList.size() > 0) {
            throw new BusinessException("请先删除对应的客户(商圈)！");
        }

        return mapper.deleteById(companyId);
    }

    @Transactional
    public int saveOrUpdate(SysCompany entity) {
        SysCompany company = this.selectByName(entity.getName(), entity.getId(), entity.getType());
        if (company != null) {
            throw new BusinessException("该名称已被占用");
        }

        if (entity.getId() == null) {
            mapper.saveIgnoreNull(entity);
            if (entity.getType() == 1) { //服务商
                entity.setCode(entity.getId().toString());
            } else {//代理商
                entity.setCode(entity.getParentCode() + "-" + entity.getId());
            }

            return mapper.updateIgnoreNull(entity);
        } else {
            return mapper.updateIgnoreNull(entity);
        }
    }

    /**
     * 查询所有权限内的所有服务商或者代理商
     *
     * @param code
     * @param type
     * @return
     */
    public List<SysCompany> selectAllCompany(String code, Integer type) {
        Query query = new Query();
        if (StringUtils.isNotBlank(code)) {
            query.likeRight("code", code);
        }
        if (type != null) {
            query.eq("type", type);
        }

        return mapper.list(query);
    }

    public SysCompany selectById(Long id) {
        return mapper.getById(id);
    }

    public SysCompany selectByCode(String code) {
        return mapper.getByColumn("code", code);
    }
    public SysCompany selectByWxMchId(String wxMchId) {
        return mapper.getByColumn("wx_mch_id", wxMchId);
    }

    private SysCompany selectByName(String name, Long id, Integer type) {
        Query query = new Query();
        query.eq("name", name);
        query.eq("type", type);
        if (id != null) {
            query.notEq("id", id);
        }
        return mapper.getByQuery(query);
    }

    public List selectAgentTree(String loginCode) {
        //返回数据第一级list
        List dataList = new ArrayList();
        List<SysCompany> serviceList = this.selectAllCompany(loginCode, 1);
        List<SysCompany> agentList = this.selectAllCompany(loginCode, 2);

        if (serviceList.size() > 0) {
            for (SysCompany service : serviceList) {
                //第一级节点
                TreeData map = new TreeData(service.getName(), service.getCode());
                Map<String, List<SysCompany>> agentCollect = agentList.stream().collect(Collectors.groupingBy(SysCompany::getParentCode));
                List<SysCompany> agents = agentCollect.get(service.getCode());
                if (agents != null) {
                    //第二级list
                    List agentArray = new ArrayList();
                    for (SysCompany agent : agents) {
                        //第二级节点
                        TreeData agentObject = new TreeData(agent.getName(), agent.getCode());
                        agentArray.add(agentObject);
                    }
                    //添加第二级
                    map.setChildren(agentArray);
                }
                //添加第一级
                dataList.add(map);
            }
        } else {
            for (SysCompany agent : agentList) {
                //第二级节点
                TreeData agentObject = new TreeData(agent.getName(), agent.getCode());
                dataList.add(agentObject);
            }
        }
        return dataList;
    }

    /**
     * 申请提现
     *
     * @param id
     * @param settleAmount
     */
    @Transactional
    public int createCustomerFlow(Long id, Integer settleAmount) {
        if (settleAmount <= 0) {
            throw new BusinessException("提现金额不能小于0");
        }
        SysCompany customer = this.selectById(id);
        if (settleAmount > customer.getProfitAmount()) {
            throw new BusinessException("提现金额不能大于可用余额");
        }
        customer.setProfitAmount(customer.getProfitAmount() - settleAmount);
        mapper.updateIgnoreNull(customer);

        return agentFlowService.save(id, settleAmount);
    }

    public void updateProfitAmount(Integer amount, Long id) {
        mapper.updateProfitAmount(amount, id);
    }
}
